package net.soevar.action;

import java.util.List;
import java.util.Set;

import net.soevar.common.Common;
import net.soevar.common.CommonPrivilages;
import net.soevar.database.hibernate.HibernateUtil;
import net.soevar.database.model.AthMenu;
import net.soevar.database.model.AthRole;
import net.soevar.database.model.AthUser;
import net.soevar.ui.util.CheckForParentScript;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;
import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.Executions;
import org.zkoss.zk.ui.Sessions;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.EventListener;
import org.zkoss.zk.ui.util.GenericAutowireComposer;
import org.zkoss.zkplus.theme.Themes;
import org.zkoss.zul.Image;
import org.zkoss.zul.Include;
import org.zkoss.zul.Messagebox;
import org.zkoss.zul.North;
import org.zkoss.zul.Popup;
import org.zkoss.zul.Tab;
import org.zkoss.zul.Tabbox;
import org.zkoss.zul.Tabpanel;
import org.zkoss.zul.Textbox;
import org.zkoss.zul.Tree;
import org.zkoss.zul.Treechildren;
import org.zkoss.zul.Treeitem;
import org.zkoss.zul.West;
import org.zkoss.zul.Window;

public class MainAction extends GenericAutowireComposer {
	private static final long serialVersionUID = 5073902497010336165L;

	private Tabbox iframe;
	private Tree menubar;

	private AthUser athuser;

	private Popup popupmenu;
	private West navigation;
	private North mycenter;

	public void doAfterCompose(Component comp) throws Exception {
		// TODO Auto-generated method stub
		super.doAfterCompose(comp);
		//Themes.setTheme(execution, "silvertail");

		if (popupmenu != null && iframe != null) {
			iframe.addEventListener("onClick", new EventListener() {

				@Override
				public void onEvent(Event arg0) throws Exception {
					popupmenu.close();
				}
			});
		}
		Sessions.getCurrent().setAttribute("iframe", iframe);

		athuser = Common.getCurrentFromSpringUser();
		session.setAttribute("usersTemp", athuser);

		// System.out.println("athuser: " + athuser);
		//
		// System.out.println("session.getAttribute(\"usersTemp\") = "
		// + session.getAttribute("usersTemp"));
		if (session.getAttribute("usersTemp") == null) {
			session.removeAttribute("usersTemp");
			execution.sendRedirect("/logoff");
			return;
		}
		// menubar.setZclass("z-vfiletree");
		AthUser user = Common.getCurrentUser();
		// System.out.println("athuser: " + athuser + ", user: " + user);

		// if (user.getFakultas() != null) {
		// Session session = Common.getManualSession();
		//
		// GambarFakultas gambarFakultas = (GambarFakultas) session
		// .createCriteria(GambarFakultas.class)
		// .add(Restrictions.eq("fakultas", user.getFakultas()))
		// .setMaxResults(1).uniqueResult();
		// if (gambarFakultas != null) {
		// if (gambarFakultas.getGambarHeader() != null) {
		// AImage aImage = new AImage("gambar_header", gambarFakultas
		// .getGambarHeader().getBinaryStream());
		// header_image.setWidth("100%");
		// header_image.setHeight("70px");
		// header_image.setContent(aImage);
		//
		// }
		//
		// }
		//
		// }

		loadTree();
		// page.getFirstRoot().appendChild(new CheckForParentScript());
	}

	public void onTutupPopup(Event event) {
		if (popupmenu != null) {
			popupmenu.close();
		}
	}

	public void onPopup(Event event) {
		// popupmenu.setVisible(true);
		if (iframe == null) {
			popupmenu.open(page.getFirstRoot(), "overlap_before");
		} else {
			popupmenu.open(iframe, "overlap_before");
		}
	}

	private synchronized Boolean hasChild(Integer root, Set<AthMenu> menus) {
		for (AthMenu menu : menus) {
			if (menu.getRoot().equals(root)) {
				return true;
			}
		}
		return false;
	}

	private void closeNavigasi() {
		if (navigation != null) {
			navigation.setOpen(false);
		}

		if (popupmenu != null) {
			popupmenu.close();
		}
	}

	private void createRootSubMenu(final Tabbox iframe, Integer root,
			Set<AthMenu> menus, Treeitem parenttreeitem) {
		Treechildren tc1 = new Treechildren();
		tc1.setParent(parenttreeitem);
		for (final AthMenu menu : menus) {
			if (menu.getStatus() != null && !menu.getStatus()) {
				continue;
			}
			if (menu.getRoot().equals(root)) {
				Boolean ada = hasChild(menu.getChild(), menus);
				if (ada) {
					Treeitem treeitem = new Treeitem(menu.getLabel(),
							menu.getUrl());
					treeitem.setOpen(false);
					treeitem.setParent(tc1);
					if (menu.getIcon() != null
							&& !menu.getIcon().trim().equals("")) {
						treeitem.setImage(menu.getIcon().trim());
					} else {
						treeitem.setImage("/include/img/menu-dir.png");
					}
					createRootSubMenu(iframe, menu.getChild(), menus, treeitem);
				} else {
					Treeitem treeitem = new Treeitem(menu.getLabel(),
							menu.getUrl());
					treeitem.setOpen(false);
					treeitem.setParent(tc1);
					if (menu.getIcon() != null
							&& !menu.getIcon().trim().equals("")) {
						treeitem.setImage(menu.getIcon().trim());
					} else {
						treeitem.setImage("/include/img/menu-none.png");
						treeitem.addEventListener("onClick",
								new EventListener() {
									@SuppressWarnings({})
									public void onEvent(Event event)
											throws Exception {

										closeNavigasi();
										// if (mycenter != null) {
										// mycenter.detach();
										// mycenter = null;
										// }

										Sessions.getCurrent().setAttribute(
												"currentMenu", menu);

										Common.launchMenu(menu);
									}
								});
					}
				}
			}
		}

	}

	public synchronized Treechildren createTreeMenu(final Tabbox iframe,
			Tree menubar, AthRole job) {
		final Set<AthMenu> menus = job.getMenus();
		Treechildren tc1 = new Treechildren();
		tc1.setParent(menubar);

		for (final AthMenu menu : menus) {
			if (menu.getStatus() != null && !menu.getStatus()) {
				continue;
			}
			if (menu.getRoot().equals(0)) {

				Boolean ada = hasChild(menu.getChild(), menus);
				if (ada) {
					Treeitem treeitem = new Treeitem(menu.getLabel(),
							menu.getUrl());
					treeitem.setParent(tc1);
					if (menu.getIcon() != null
							&& !menu.getIcon().trim().equals("")) {
						treeitem.setImage(menu.getIcon().trim());
					} else {
						treeitem.setImage("/include/img/menu-dir.png");
					}
					treeitem.setOpen(false);
					createRootSubMenu(iframe, menu.getChild(), menus, treeitem);
				} else {
					Treeitem treeitem = new Treeitem(menu.getLabel(),
							menu.getUrl());
					treeitem.setParent(tc1);
					if (menu.getIcon() != null
							&& !menu.getIcon().trim().equals("")) {
						treeitem.setImage(menu.getIcon().trim());
					} else {
						treeitem.setImage("/include/img/menu-doc.png");
					}
					treeitem.setOpen(false);
					treeitem.addEventListener("onClick", new EventListener() {
						public void onEvent(Event event) throws Exception {

							Sessions.getCurrent().setAttribute("currentMenu",
									menu);

							closeNavigasi();
							// if (mycenter != null) {
							//
							// mycenter.detach();
							// mycenter = null;
							// }

							Common.insertToTab(iframe, menu);

						}
					});
				}
			}
		}

		// for (final AthMenu menu : menus) {
		// if (menu.getRoot().equals(0)) {
		//
		// Boolean ada = hasChild(menu.getChild(), menus);
		// if (ada) {
		// Treeitem treeitem = new Treeitem(menu.getLabel(),
		// menu.getUrl());
		// treeitem.setParent(tc1);
		// treeitem.setOpen(false);
		// createRootSubMenu(iframe, menu.getChild(), menus, treeitem);
		// } else {
		// Treeitem treeitem = new Treeitem(menu.getLabel(),
		// menu.getUrl());
		// treeitem.setParent(tc1);
		//
		// treeitem.setOpen(false);
		// treeitem.addEventListener("onClick", new EventListener() {
		// @SuppressWarnings("unchecked")
		// public void onEvent(Event event) throws Exception {
		// // System.out.println("Sip banget");
		// if (menu.getUrl() != null
		// && menu.getUrl().trim()
		// .endsWith("login.zul")) {
		// Messagebox.show("Keluar dari Aplikasi ?",
		// "Question", Messagebox.OK
		// | Messagebox.CANCEL,
		// Messagebox.QUESTION,
		// new EventListener() {
		//
		// @Override
		// public void onEvent(Event event)
		// throws Exception {
		// int i = new Integer(event
		// .getData().toString());
		// if (i == Messagebox.CANCEL)
		// return;
		// session.removeAttribute("usersTemp");
		// execution
		// .sendRedirect("/logoff");
		//
		// }
		// });
		// } else {
		// // iframe
		// // .setSrc(menu.getUrl() == null
		// // || menu.getUrl().trim().equals(
		// // "") ? "blank.zul"
		// // : menu.getUrl().trim());
		// List<Tab> tabs = iframe.getTabs().getChildren();
		// boolean ada = false;
		// for (Tab tab : tabs) {
		// if (tab.getLabel().equalsIgnoreCase(
		// menu.getLabel())) {
		// ada = true;
		// tab.setSelected(true);
		// break;
		// }
		// }
		// if (!ada) {
		// Tab tab = new Tab(menu.getLabel());
		// tab.setClosable(true);
		// tab.setSelected(true);
		// iframe.getTabs().appendChild(tab);
		// Tabpanel tabpanel = new Tabpanel();
		// Include include = new Include(menu.getUrl()
		// .trim());
		// include.setWidth("100%");
		// include.setHeight("100%");
		// tabpanel.appendChild(include);
		// iframe.getTabpanels().appendChild(tabpanel);
		// }
		// }
		// }
		// });
		// }
		// }
		// }
		return tc1;
	}

	public synchronized void loadTree() {
		AthUser users = (AthUser) Sessions.getCurrent().getAttribute(
				"usersTemp");
		if (users == null || users.getUserRole() == null
				|| users.getUserRole().getMenus() == null)
			return;

		Session ses = HibernateUtil.currentSession();
		Criteria criteria = ses.createCriteria(AthUser.class);
		criteria.add(Restrictions.idEq(users.getUserId()));
		users = ((AthUser) criteria.uniqueResult());
		Sessions.getCurrent().setAttribute("users", users);
		users = (AthUser) Sessions.getCurrent().getAttribute("users");
		Treechildren tc1;
		// if (((AthUser) Sessions.getCurrent().getAttribute("usersTemp"))
		// .getMahasiswa() == null) {
		// Tbmrole tbmrole = (Tbmrole) HibernateUtil.currentSession().load(
		// Tbmrole.class, users.getUserRole().getRoleId());
		// tc1 = createTreeMenu(iframe, menubar, tbmrole);
		// } else {
		users = (AthUser) Sessions.getCurrent().getAttribute("usersTemp");
		AthRole athrole = (AthRole) HibernateUtil.currentSession().load(
				AthRole.class, users.getUserRole().getRoleId());
		tc1 = createTreeMenu(iframe, menubar, athrole);
		// }

		// tc1.setParent(menubar);

		Treeitem menuitem = new Treeitem("Keluar Aplikasi", "");
		menuitem.setOpen(false);
		menuitem.setImage("/include/img/close.png");
		menuitem.setParent(tc1);
		menuitem.addEventListener("onClick", new EventListener() {
			public void onEvent(Event event) throws Exception {
				onKeluar(event);
			}
		});
	}

	public void onKeluar(Event event) throws Exception {
		Messagebox.show("Keluar dari Aplikasi ?", "Pertanyaan", Messagebox.OK
				| Messagebox.CANCEL, Messagebox.QUESTION, new EventListener() {

			@Override
			public void onEvent(Event event) throws Exception {

				int i = new Integer(event.getData().toString());
				if (i == Messagebox.CANCEL)
					return;
				session.removeAttribute("usersTemp");
				Common.goLogoff();
			}
		});

	}

}
